from flask import Flask, render_template, url_for, session, redirect, request
from . import admin
from app.models import Article, Oplog, db, User, Admin
import datetime


@admin.route('/')
def admin():
    admin = Admin.query.filter_by(user_name=session['username']).first()
    if request.method == 'POST':
        if admin is not None:
            item = User.query.all()
            arc = Article.query.all()
            ip = request.remote_addr
            opuser = session['username']
            op1 = "Admin Manage Success"
            date = datetime.datetime.now()
            OPT = Oplog(op_user=opuser, op=op1, IP=ip, op_date=date)
            db.session.add(OPT)
            db.session.commit()
            return render_template('admin.html', item=item, arc=arc)
        else:
            return '没有访问权限，<a href="../">单机此处</a>返回'
    elif request.method == 'GET' and request.args.get('del') is not None:
        if admin is not None:
            itEm_id = request.args.get('del')
            itEm = User.query.filter_by(id=itEm_id).first()
            if itEm is not None:
                db.session.delete(itEm)
                ip = request.remote_addr
                opuser = session['username']
                op1 = "User delete whose id is" + itEm_id
                date = datetime.datetime.now()
                OPT = Oplog(op_user=opuser, op=op1, IP=ip, op_date=date)
                db.session.add(OPT)
                db.session.commit()
            itEm_name=request.args.get('del')
            itEmA=Article.query.filter_by(arc_name=itEm_name).first()
            if itEmA is not None:
                db.session.delete(itEmA)
                ip = request.remote_addr
                opuser = session['username']
                op1 = "Article Delete " +"whose name is" + itEm_name;
                date = datetime.datetime.now()
                OPT = Oplog(op_user=opuser, op=op1, IP=ip, op_date=date)
                db.session.add(OPT)
                db.session.commit()
            return redirect('/admin')
    else:
        if admin is not None:
            item = User.query.all()
            arc = Article.query.all()
            opl = Oplog.query.all()
            ip = request.remote_addr
            opuser = session['username']
            op1 = "Admin Manage Fail"
            date = datetime.datetime.now()
            OPT = Oplog(op_user=opuser, op=op1, IP=ip, op_date=date)
            db.session.add(OPT)
            db.session.commit()
            return render_template('admin.html', item=item, arc=arc, content=opl)
        else:
            return '没有访问权限，<a href="../">单机此处</a>返回'
